package com.leo.utils;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列号 反序列化
 * 
 * @author leo
 * 
 */
public class SerializableUtils {
	private SerializableUtils() {

	}

	/**
	 * 序列号
	 * @param obj
	 * @param fileName
	 */
	public static void to(Context context,Object obj, String fileName) {
		File filesDir = context.getFilesDir();
		String path = String.format(filesDir + "/%s.bin",fileName);
		ObjectOutputStream oos;
		try {
			// 创建一个ObjectOutputStream输出流
			oos = new ObjectOutputStream(new FileOutputStream(path));
			// 将per对象写入输出流
			oos.writeObject(obj);
		} catch (Exception e) {
		}
	}

	/**
	 * 反序列化
	 * @param fileName
	 * @return
	 */
	public static Object from(Context context,String fileName,long interval) {
		File filesDir = context.getFilesDir();
		String path = String.format(filesDir + "/%s.bin",fileName);
		ObjectInputStream ois = null;
		try {
			File file = new File(path);
			if(System.currentTimeMillis() - file.lastModified() > interval){
				return null;
			}
			ois = new ObjectInputStream(new FileInputStream(file));
			Object object = ois.readObject();
			ois.close();
			return object;
		} catch (Exception e) {
		}
		return null;
	}
	
	public static Object from(Context context,String fileName) {
		return from(context,fileName,  60 * 60 * 1000);
	}
}
